import sdk = require('/utils/WebIM')
//@ts-ignore
// eslint-disable-next-line no-undef
const WebIM = (wx.WebIM = sdk.default)
import { userApi } from '/api/user'
import { checkAuth, getNotifications, getUser, getUsers } from '/store/actions'
import { getServer, isLogin } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    access: GlobalData.access,
    info: {},
    authentication: false,
    remove: false,
    arr: [] as any,
    groupName: {} as any,
    unReadSpotNum: 0 as any,
    messageNum: 0,
    unReadNoticeNum: 0,
    unReadTotalNotNum: 0,
  },
  async onLoad() {
    const me = this
    //监听加好友申请
    $event.on('em.xmpp.subscribe', this, () => {
      me.setData({
        messageNum: GlobalData.saveFriendList.length,
        unReadTotalNotNum:
          GlobalData.saveFriendList.length + GlobalData.saveGroupInvitedList.length,
      })
    })

    //监听解散群
    $event.on('em.xmpp.invite.deleteGroup', this, () => {
      me.listGroups()
      me.getRoster()
      me.getChatList()
      me.setData({
        // arr: me.getChatList(),
        messageNum: GlobalData.saveFriendList.length,
      })
    })

    //监听未读消息数
    $event.on('em.xmpp.unreadspot', this, () => {
      me.getChatList()
      me.setData({
        unReadSpotNum: GlobalData.unReadMessageNum > 99 ? '99+' : GlobalData.unReadMessageNum,
      })
    })

    //监听未读加群“通知”
    $event.on('em.xmpp.invite.joingroup', this, () => {
      me.setData({
        unReadNoticeNum: GlobalData.saveGroupInvitedList.length,
        unReadTotalNotNum:
          GlobalData.saveFriendList.length + GlobalData.saveGroupInvitedList.length,
      })
    })

    $event.on('em.xmpp.contacts.remove', this, () => {
      me.getChatList()
      me.getRoster()
      me.setData({
        arr: me.getChatList(),
        unReadSpotNum: GlobalData.unReadMessageNum > 99 ? '99+' : GlobalData.unReadMessageNum,
      })
    })
    $event.on('after:login', this, async () => {
      this.getList()
    })
    $event.on('after:notification', this, () => {
      this.getList()
      this.setData({ remove: true })
    })
    $event.on('message:showMessageDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          showMeesageDot: isShow,
        })
      }
    })
    $event.on('message:showMineDot', this, (isShow) => {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          showMineDot: isShow,
        })
      }
    })
  },
  async onShow() {
    // 自定义tab
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1,
      })
    }
    $event.on('after:boot', this, () => {
      this.setData({
        navigationHeight: GlobalData.navigationHeight,
        access: GlobalData.access,
        unReadSpotNum: GlobalData.unReadMessageNum > 99 ? '99+' : GlobalData.unReadMessageNum,
        messageNum: GlobalData.saveFriendList.length,
        unReadNoticeNum: GlobalData.saveGroupInvitedList.length,
        unReadTotalNotNum:
          GlobalData.saveFriendList.length + GlobalData.saveGroupInvitedList.length,
      })
    })
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
      unReadSpotNum: GlobalData.unReadMessageNum > 99 ? '99+' : GlobalData.unReadMessageNum,
      messageNum: GlobalData.saveFriendList.length,
      unReadNoticeNum: GlobalData.saveGroupInvitedList.length,
      unReadTotalNotNum: GlobalData.saveFriendList.length + GlobalData.saveGroupInvitedList.length,
    })
    if (isLogin()) {
      this.getChatList()
      this.getList()
    } else {
      await checkAuth()
    }
    if (this.data.remove) {
      getNotifications()
      this.setData({ remove: false })
    }
  },
  async onPullDownRefresh() {
    if (isLogin()) {
      this.getList()
    } else {
      await checkAuth()
    }
    wx.stopPullDownRefresh()
  },
  async getList() {
    // 获取用户权限
    if (GlobalData.userAbilities.length == 0) {
      GlobalData.userAbilities = await userApi.abilitiesList()
      $event.emit('after:abilities')
    }
    const abilities: any = GlobalData.userAbilities
    const token = wx.getStorageSync(`${getServer()}/accessToken`).data
    const user = wx.getStorageSync(`${getServer()}/logged`).data || {}
    const { shopkeeper, ability_name } = GlobalData.mall
    if (token) {
      const info = await userApi.getNewsList()
      const messageNum =
        info.badges.system +
        info.badges.comment +
        info.badges.like +
        info.badges.reward +
        info.badges.answer +
        info.badges.mall_selling_commodity +
        info.badges.selling_knowledge +
        (GlobalData.unReadMessageNum || 0)

      $event.emit('message:showMessageDot', messageNum > 0)
      $event.emit('message:showMineDot', info.badges.following > 0)

      // messageNum > 0
      //   ? wx.showTabBarRedDot({
      //     index: 3,
      //   })
      //   : wx.hideTabBarRedDot({
      //     index: 3,
      //   })
      this.setData({
        info,
      })
    }
    const isShopper =
      shopkeeper === 'verification' && user && user.verification && user.verification.state === 1
        ? true
        : shopkeeper === 'ability' &&
          abilities &&
          abilities.some((v: any) => v.name === ability_name)

    const author = GlobalData.knowledge.author
    const authorAbility = GlobalData.knowledge.ability_name
    const isKownledgor =
      author === 'verification' && user && user.verification && user.verification.state === 1
        ? true
        : author === 'ability' && abilities && abilities.some((v: any) => v.name === authorAbility)
    this.setData({
      authentication: isShopper || isKownledgor,
    })
  },
  async toDetail(e: WechatMiniprogram.CustomEvent) {
    await checkAuth()
    const id = e.currentTarget.dataset.id
    const number = e.currentTarget.dataset.number
    if (id == 0) {
      wx.navigateTo({
        url: `/pages/news/systemMsg/systemMsg?id=${id}&number=${number}`,
      })
    } else if (id < 4) {
      wx.navigateTo({
        url: `/pages/news/detail/detail?id=${id}&number=${number}`,
      })
    } else {
      wx.navigateTo({
        url: `/mall/order/order?id=${id}&number=${number}`,
      })
    }
  },
  onDownload() {
    $event.emit('download')
  },
  onHide() {},
  listGroups() {
    const me = this
    return WebIM.conn.getGroup({
      limit: 50,
      success: function (res: { data: never[] }) {
        const groupName = {}
        const listGroup = res.data || []
        listGroup.forEach((item) => {
          //@ts-ignore
          // eslint-disable-next-line no-undef
          groupName[item.groupid] = item.groupname
        })

        me.setData({
          groupName,
        })
        wx.setStorage({
          key: 'listGroup',
          data: res.data,
        })
        me.getChatList()
      },
      error: function (err: any) {
        console.log(err)
      },
    })
  },

  getRoster() {
    const me = this
    const rosters = {
      success(roster: string | any[]) {
        const member = []
        for (let i = 0; i < roster.length; i++) {
          if (roster[i].subscription == 'both') {
            member.push(roster[i])
          }
        }
        wx.setStorage({
          key: 'member',
          data: member,
        })
        me.setData({ member: member })
        me.listGroups()
        //if(!systemReady){
        $event.emit('em.main.ready')
        me.setData({
          arr: me.getChatList(),
          unReadSpotNum: GlobalData.unReadMessageNum > 99 ? '99+' : GlobalData.unReadMessageNum,
        })
      },
      error(err: any) {
        console.log(err)
      },
    }
    WebIM.conn.getRoster(rosters)
  },
  getChatList() {
    const myName = GlobalData.imVersion + getUser().id
    const me = this
    wx.getStorageInfo({
      success: function (res) {
        const storageKeys = res.keys
        const newChatMsgKeys = [] as any
        const historyChatMsgKeys = [] as any
        const len = myName.length
        storageKeys.forEach((item) => {
          if (item.slice(-len) == myName && item.indexOf('rendered_') == -1) {
            newChatMsgKeys.push(item)
          } else if (item.slice(-len) == myName && item.indexOf('rendered_') > -1) {
            historyChatMsgKeys.push(item)
          }
        })
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        cul.call(me, newChatMsgKeys, historyChatMsgKeys)
      },
    })

    function cul(newChatMsgKeys: string[], historyChatMsgKeys: string | any[]) {
      const array = []
      let lastChatMsg
      for (let i = 0; i < historyChatMsgKeys.length; i++) {
        const index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9))
        if (index > -1) {
          const newChatMsgs = wx.getStorageSync(newChatMsgKeys[index]) || []
          if (newChatMsgs.length) {
            lastChatMsg = newChatMsgs[newChatMsgs.length - 1]
            lastChatMsg.unReadCount = newChatMsgs.length
            if (lastChatMsg.unReadCount > 99) {
              lastChatMsg.unReadCount = '99+'
            }
            const dateArr = lastChatMsg.time.split(' ')[0].split('-')
            const timeArr = lastChatMsg.time.split(' ')[1].split(':')
            const month = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2]
            lastChatMsg.dateTimeNum = `${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`
            // lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}时${timeArr[1]}分`
            newChatMsgKeys.splice(index, 1)
          } else {
            const historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i])
            if (historyChatMsgs.length) {
              lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1]
              const dateArr = lastChatMsg.time.split(' ')[0].split('-')
              const timeArr = lastChatMsg.time.split(' ')[1].split(':')
              const month = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2]
              lastChatMsg.dateTimeNum = `${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`
              // lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}时${timeArr[1]}分`
            }
          }
        } else {
          const historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i])
          if (historyChatMsgs.length) {
            lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1]
            const dateArr = lastChatMsg.time.split(' ')[0].split('-')
            const timeArr = lastChatMsg.time.split(' ')[1].split(':')
            const month = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2]
            lastChatMsg.dateTimeNum = `${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`
            // lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}时${timeArr[1]}分`
          }
        }
        if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
          lastChatMsg.groupName = me.data.groupName[lastChatMsg.username]
        }
        lastChatMsg && lastChatMsg.username != myName && array.push(lastChatMsg)
      }

      for (let i = 0; i < newChatMsgKeys.length; i++) {
        const newChatMsgs = wx.getStorageSync(newChatMsgKeys[i]) || []
        if (newChatMsgs.length) {
          lastChatMsg = newChatMsgs[newChatMsgs.length - 1]
          lastChatMsg.unReadCount = newChatMsgs.length
          if (lastChatMsg.unReadCount > 99) {
            lastChatMsg.unReadCount = '99+'
          }
          const dateArr = lastChatMsg.time.split(' ')[0].split('-')
          const timeArr = lastChatMsg.time.split(' ')[1].split(':')
          const month = dateArr[2] < 10 ? '0' + dateArr[2] : dateArr[2]
          lastChatMsg.dateTimeNum = `${dateArr[1]}${month}${timeArr[0]}${timeArr[1]}${timeArr[2]}`
          // lastChatMsg.time = `${dateArr[1]}月${dateArr[2]}日 ${timeArr[0]}时${timeArr[1]}分`
          if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
            lastChatMsg.groupName = me.data.groupName[lastChatMsg.username]
          }
          lastChatMsg.username != myName && array.push(lastChatMsg)
        }
      }

      array.sort((a, b) => {
        return b.dateTimeNum - a.dateTimeNum
      })
      getUsers(array).then((arr) => {
        me.setData({
          arr,
        })
      })
    }
  },
  //	单聊
  into_singleChatRoom(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item: detail },
      },
    } = e
    const my = GlobalData.imVersion + getUser().id
    const nameList = {
      myName: my,
      your: detail.username,
      name: getUser().name,
      yourname: detail.user ? detail.user.name : detail.username,
    }
    wx.navigateTo({
      url: '/pages/news/chatroom/chatroom?username=' + JSON.stringify(nameList),
    })
  },
})
